package com.onec.service.route.service.impl;

import com.onec.service.api.enums.ProductEnum;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.api.enums.error.RouteErrorEnum;
import com.onec.service.api.exception.RouteException;
import com.onec.service.route.dao.RouteChannelInfoRepository;
import com.onec.service.route.entity.RouteChannelInfo;
import com.onec.service.route.service.RouteChannelInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author onec
 * @see
 */
@Service
public class RouteChannelInfoServiceImpl implements RouteChannelInfoService {

    @Autowired
    RouteChannelInfoRepository channelInfoRepository;

    @Override
    public List<RouteChannelInfo> getAvailableRouteChannel(ProductEnum product) {

        List<RouteChannelInfo> routeChannelInfos = channelInfoRepository.findByProduct(product);
        if (routeChannelInfos.size() > 0) {
            routeChannelInfos = routeChannelInfos
                    .stream()
                    .filter(e -> StatusEnum.isSuccess(e.getStatus()))
                    .collect(Collectors.toList());
        }
        if (routeChannelInfos.size() <= 0) {
            throw new RouteException(RouteErrorEnum.MERCHANT_TRADE_CHANNEl_DOING, product.name());
        }
        return routeChannelInfos;
    }

    @Override
    public List<RouteChannelInfo> findByBusinessNo(String businessNo) {
        List<RouteChannelInfo> routeChannelInfos = channelInfoRepository.findByBusinessNo(businessNo);
        if (routeChannelInfos.size() > 0) {
            routeChannelInfos = routeChannelInfos
                    .stream()
                    .filter(e -> StatusEnum.isSuccess(e.getStatus()))
                    .collect(Collectors.toList());
        }
        if (routeChannelInfos.size() <= 0) {
            throw new RouteException(RouteErrorEnum.MERCHANT_TRADE_CHANNEl_DOING, businessNo);
        }
        return routeChannelInfos;
    }

    @Override
    public RouteChannelInfo getRouteChannelInfoId(Long routeChannelId) {

        Optional<RouteChannelInfo> routeChannelInfo = channelInfoRepository.findById(routeChannelId);
        if (routeChannelInfo.isEmpty()) {
            throw new RouteException(RouteErrorEnum.SUCCESS, "");
        }
        return routeChannelInfo.get();
    }
}
